#include "server.h"
#include "ui_server.h"
#include "QFile"

Server::Server(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Server)
{
    ui->setupUi(this);

    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("C:/Codefield/CODE_QT_OWN/build-ExpressSys_v3.0/build-client/Database.db");
    db.open();

    timer = new QTimer(this);

    tcpServer = new QTcpServer(this);
    connect(ui->createBtn, &QPushButton::clicked, this, &Server::startServer);
    connect(tcpServer, &QTcpServer::newConnection, this, &Server::onNewConnection);
    connect(timer, &QTimer::timeout, [=](){
        for (int i = 0; i < tcpClientList.size(); i++)
            if (tcpClientList.at(i)->state() == QAbstractSocket::UnconnectedState)
                tcpClientList.removeAt(i--);
    });

}

Server::~Server()
{
    delete ui;
}

void Server::startServer()
{
    ip = QHostAddress::Any;
    port = ui->portEdit->text().toShort();
    QStringList list;
    if (tcpServer->listen(ip, port)) {

        QString str = "启动服务器成功...";
        list.append(str);
        str = QString("IP: 127.0.0.1  port: %1").arg(QString::number(port));
        list.append(str);
        ui->listWidget->addItems(list);
        timer->start(3000);
    }
    else {
        QString str = "启动服务器失败";
        ui->listWidget->addItem(str);
    }
}

void Server::onReadyRead()
{
    qDebug() << "接收信息";


    QString str;
    QSqlQuery query;
    QByteArray buf;
    for (int i = 0; i < tcpClientList.size(); i++) {
        if (tcpClientList.at(i)->bytesAvailable()) {
            buf = tcpClientList.at(i)->readAll();
            if (*(buf.end()-1) == '#') {

                buf.remove(buf.size()-1, 1);
                ui->listWidget->addItem(buf);
                return;
            }
            str = QString(buf);
            qDebug() << str;
            if (query.exec(str)) {
                qDebug() << "客户端数据库操作成功server";
                //qDebug() << QString(buf);
            }
        }
    }



}

void Server::onNewConnection()
{
    QTcpSocket *tcpClient = tcpServer->nextPendingConnection();
    tcpClientList.append(tcpClient);
    connect(tcpClient, &QTcpSocket::readyRead, this, &Server::onReadyRead);
    connect(tcpClient, &QTcpSocket::disconnected, [=](){
        QString str = "客户端断开连接，在线数量：" + QString::number(tcpClientList.size()-1);
        ui->listWidget->addItem(str);
    });

    QString str = "建立连接，连接数：" + QString::number(tcpClientList.size());
    qDebug() << str;
    ui->listWidget->addItem(str);

}


